﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using nanoCMS.Core.WebProviders.ViewModels;

namespace nanoCMS.Core.WebProviders.HtmlHelpers {
	public static class CustomRenderActionHelper {


		private static RouteValueDictionary MergeRouteValues(RouteValueDictionary routeValues)
		{
			throw new NotImplementedException();
		}


		public static MvcHtmlString Display(this HtmlHelper htmlHelper, object elements)
		{
			string elementKey = string.Empty;
			try
			{
				if (htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString.Get("elementKey") != null)
					elementKey = htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString.Get("elementKey");
			}catch{}

			


			foreach (var item in (List<ViewElementVM>)elements) {

				if (!string.IsNullOrEmpty(elementKey) && item.ElementKey == elementKey)
				{
					
					foreach (var param in htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
					{
						if(item.RouteValues.ContainsKey(param))
						{
							item.RouteValues.Remove(param);
						}
						if(param == "elementKey") continue;
						if (param == "action")
						{
							item.Action = htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString.Get(param);
							continue;
							
						}
						

						item.RouteValues.Add(param, htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString.Get(param));
					}

				}
				item.RouteValues.Add("elementKey", item.ElementKey);
				htmlHelper.RenderAction(item.Action, item.RouteValues);
			}
			return MvcHtmlString.Empty;
		}
	}
}
